/**
 * Created by wangzm on 2016/7/7.
 */
var thisErpId = 1;
var showCallFun = ''; //模态框回调函数;
var common = function () {
    this.ua = navigator.userAgent.toLowerCase();
    var comProtocolUrl = window.location.protocol; //获取url请求的协议部分
    var comHostUrl = window.location.host; //获取url请求的host
    comHostUrl = comProtocolUrl + '//' + comHostUrl;
    this.stoneImgUrl = comHostUrl;
    this.hostUrl = comHostUrl + '/slsw/';
    this.hostUrl = 'https://mapit.beiface.com/'
    this.ajaxOption = {
        url: '',
        type: 'post',
        data: {},
        dataType: 'json',
        callback: 'callback',
        error: this.errorFun
    };
    this.date = new Date();
};
common.prototype = {
    //获取地址栏指定参数
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r !== null)
            return unescape(r[2]);
        return null;
    },
    //获取地址栏指定参数.不转义
    getQueryStringActivity: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]); //不转义
        return null;
    },
    //表单序列号字符串转json对象
    strToObj: function (str) {
        try {
            str = str.replace(/&/g, "','");
            str = str.replace(/=/g, "':'");
            str = str.replace(/[\r\n]/g, ""); //清除回车符号
            str = "({'" + str + "'})";
            return eval(str);
        } catch (e) {
            console.log('转化异常：' + e);
            return false;
        }
    },
    //将字符串转化成json对象
    getJsonObj: function (str) {
        if (str) {
            try {
                return JSON.parse(str);
            } catch (e) {
                console.log("封装成JSON对象出错：" + e);
                return false;
            }
        } else {
            return false;
        }
    },
    //设置页面title
    setHtmlTitle: function (str) {
        $(document).attr("title", str);
    },
    //格式化身份证
    formatIdCard: function (idCard) {
        idCard += '';
        return idCard.substring(0, 6) + this.star(9) + idCard.substring(14, 18);
    },
    //格式化money
    formatMoney: function (str) {
        var money = 0;
        if (parseFloat(str) < 0) {
            return money.toFixed(2);
        } else {
            return parseFloat(str).toFixed(2);
        }
    },
    //隐藏手机中间五位
    formatPhone: function (phone) {
        phone += '';
        return phone.substring(0, 3) + this.star(5) + phone.substring(8, 11);
    },
    //替换空格，回车换行
    formatTxt: function (txt) {
        var text = cmttxt.replace(/\ +/g, ""); //去掉空格
        text = text.replace(/[ ]/g, ""); //去掉空格
        text = text.replace(/[\r\n]/g, ""); //去掉回车换行
        return text;
    },
    //星号替换
    star: function (num) {
        num = parseInt(num);
        var s = '';
        while (num > 0) {
            s += '*';
            num--;
        }
        return s;
    },
    //隐藏邮箱中间几位
    formatMail: function (txt) {
        txt += '';
        var index = txt.indexOf('@');
        return index > 3 ? txt.substring(0, index) + this.star(index - 3) + txt.substr(index) : txt;
    },
    //根据日期获取星期
    getWeek: function (str) {
        return "星期" + "日一二三四五六".charAt(new Date(str).getDay());
    },

    //根据时间戳获取日期时间
    getDateTime: function (time, fmt) {
        try {
            var now = new Date(time);
            return now.Format(fmt);
        } catch (e) {
            console.log(e);
        }
    },
    //ajax请求出错回调
    errorFun: function (e) {
        console.log(e);
        console.log('服务器异常！');
    },
    //验证浏览器ie10以下进行提示
    verBrowser: function () {
        if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE", "")) < 10) {
            alert("您的浏览器版本过低，请下载新版本的浏览器以便您有更好的体验！");
            window.open('http://se.360.cn/', '_blank');
        }
    }(),
    //是否清除搜索记录的缓存
    isClearSession: function () {
        var url = window.location.href;
        //根据页面url删除不需要的缓存数据--预防残存数据
        if (url.indexOf('friend-audit-detail') > -1) {
            sessionStorage.removeItem('friHisBackMark');
            sessionStorage.removeItem('stoHisBackMark');
            sessionStorage.removeItem('stoSeaSessionObj');
        } else if (url.indexOf('stone-img-detail') > -1) {
            sessionStorage.removeItem('stoHisBackMark');
            sessionStorage.removeItem('friHisBackMark');
            sessionStorage.removeItem('friSeaSessionObj');
        } else if (url.indexOf('friend-audit') > -1) {
            sessionStorage.removeItem('stoHisBackMark');
            sessionStorage.removeItem('stoSeaSessionObj');
        } else if (url.indexOf('stone-img') > -1) {
            sessionStorage.removeItem('friHisBackMark');
            sessionStorage.removeItem('friSeaSessionObj');
        } else {
            sessionStorage.removeItem('stoSeaSessionObj');
            sessionStorage.removeItem('stoHisBackMark');
            sessionStorage.removeItem('friSeaSessionObj');
            sessionStorage.removeItem('friHisBackMark');
        }
    }(),
};

//判断手机号是否正确
function isRegPhone(phone) {
    var re = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!re.test(phone)) {
        return true
    } else {
        return false
    }
}

//格式化特殊字符
function formatSpecStr(str) {
    var returnStr = "";
    if (str) {
        returnStr = str.replace(/&lt;/g, "<");
        returnStr = returnStr.replace(/&gt;/g, ">");
        returnStr = returnStr.replace(/&quot;/g, "'");
        returnStr = returnStr.replace(/&#39;/g, "'");
        returnStr = returnStr.replace(/&nbsp;/g, " ");
    }
    return returnStr;
}

//字符串
String.prototype.replaceAll = function (str1, str2) {
    var str = this;
    return str.replace(eval("/" + str1 + "/gi"), str2);
};
//根据时间戳获取日期时间
function getDateTime(time, fmt) {
    try {
        var now = new Date(time);
        return now.Format(fmt);
    } catch (e) {
        console.log(e);
    }
}
//时间格式化
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
//日期加减函数
function addDate(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var m = d.getMonth() + 1;
    return d.getFullYear() + '-' + m + '-' + d.getDate();
}
//比较两个日期的大小
function CompareDate(d1, d2) {
    return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
}

//页面刷新
function reload() {
    location.reload()
}

//--------------------------------------------无回调模态框----------------------------------------
//模态框HTML
function modalAlt() {
    var altHtml = '<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\n' +
        '    <div class="modal-dialog">\n' +
        '        <div class="modal-content">\n' +
        '            <div class="modal-header">\n' +
        '                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\n' +
        '                <h4 class="modal-title" id="myModalLabel">提示框</h4>\n' +
        '            </div>\n' +
        '            <div class="modal-body" id="modalBody">输入内容。</div>\n' +
        '            <div class="modal-footer">\n' +
        '                <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>\n' +
        '            </div>\n' +
        '        </div>\n' +
        '    </div> \n' +
        '</div>';
    $('body').append(altHtml);
}
//显示弹窗
function showAlt(contene, status) {
    $('#modalBody').text(contene);
    $('#myModal').modal({
        keyboard: status
    });
}
//--------------------------------------------回调模态框----------------------------------------
//回调模态框HTML
function callModalAlt() {
    var altHtml = '<div class="modal fade" id="myCallModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\n' +
        '    <div class="modal-dialog">\n' +
        '        <div class="modal-content">\n' +
        '            <div class="modal-header">\n' +
        '                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\n' +
        '                <h4 class="modal-title" id="myModalLabel">提示框</h4>\n' +
        '            </div>\n' +
        '            <div class="modal-body" id="callModalBody">输入内容。</div>\n' +
        '            <div class="modal-footer">\n' +
        '                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>\n' +
        '                <button type="button" class="btn btn-primary" onclick="hideModeFun()">确定</button>\n' +
        '            </div>\n' +
        '        </div>\n' +
        '    </div> \n' +
        '</div>';
    $('body').append(altHtml);
}
//显示弹窗
function showCallAlt(content, status, callback) {
    $('#callModalBody').text(content);
    showCallFun = callback;
    $('#myCallModal').modal({
        backdrop: status
    });
}
//执行回调并关闭弹窗
function hideModeFun() {
    showCallFun();
    $('#myCallModal').modal('hide')
};
//全局通知配置
(function toastrConfi() {
    try {
        toastr.options = {
            "positionClass": 'toast-top-center',
            "timeOut": "1000", //展现时间
        }
    } catch (e) {
        console.log('没引用toastr.js')
    }
})()
// toastrConfi();
//修改账号启用或禁用
function checkAcc(id, status, callback) {
    var cApi = new common();
    var idArr = [];
    idArr.push(id);
    idArr = JSON.stringify(idArr);
    var json = {
        url: cApi.hostUrl + 'cms/checkUserAccount.html',
        data: "weChatKey=9237B361957490BA9644A710A5E3DD84&&Data={userId:" + idArr + ",status:" + status + ",erpId:" + thisErpId + "}",
        success: function (data) {
            console.log(data);
            if (data.Result) {
                if (status == 1) {
                    toastr.success('启用成功!');
                } else {
                    toastr.success('禁用成功!')
                }
                callback();
            } else {
                showAlt('修改失败！', true);
            }
        },
        errorFun: function (e) {
            console.log(e);
        }
    };
    json = $.extend({}, cApi.ajaxOption, json);
    $.ajax(json);
}
//获取当前服务器时间
function setNowTime(callback, type) {
    var cApi = new common();
    $.get(cApi.hostUrl + 'getsystime.html', function (data) {
        data = JSON.parse(data);
        console.log(data);
        if (data.Result) {
            var time = '';
            if (type == 1) {
                time = getDateTime(data.Data.systime.time, 'yyyy-MM-dd hh:mm:ss');
            } else {
                time = getDateTime(data.Data.systime.time, 'yyyy-MM-dd');
                sessionStorage.setItem("serverTime", JSON.stringify(time));
                getNowTime();
            }
            if (callback) {
                callback(time);
            }
        }
    });
}
//保存服务器当前时间
function getNowTime() {
    var serverTime = sessionStorage.getItem("serverTime");
    serverTime = JSON.parse(serverTime);
    if (serverTime) {
        var browserTime = getDateTime(new Date(), 'yyyy-MM-dd');
        var timeDif = (new Date(browserTime.replace(/-/g, "\/"))) - (new Date(serverTime.replace(/-/g, "\/")));
        if (timeDif >= 86400000) {
            setNowTime();
        } else {
            return serverTime;
        }
    } else {
        setNowTime();
    }
}
//退出登陆按钮
$('html').on('click', '.login-out', function () {
    loginOut();
});
//退出登录
function loginOut() {
    var cApi = new common();
    var json = {
        url: cApi.hostUrl + 'cms/brlogout.html',
        data: "",
        success: function (data) {
            // console.log(data);
            localStorage.removeItem('serverPro');
            location.href = 'login.html'
        },
        errorFun: function (e) {
            console.log(e);
        }
    };
    json = $.extend({}, cApi.ajaxOption, json);
    $.ajax(json);
}
//验证手机号
function isPhoneUsed(userId, phone, pageId, callback) {
    var cApi = new common();
    var json = {
        url: cApi.hostUrl + 'cms/isPhoneUsed.html',
        data: "weChatKey=9237B361957490BA9644A710A5E3DD84&&Data={id:" + userId + ",from:" + pageId + ",phone:'" + phone + "'}",
        success: function (data) {
            console.log(data);
            if (data.Result) {
                var userKey = data.Key;
                if (data.Key == '') {
                    toastr.success('该手机号可以使用！')
                } else {
                    toastr.warning(data.MSG_CODE);
                }
                callback(userKey);
            } else {
                toastr.error(data.MSG_CODE);
                callback('1414');
            }
        },
        errorFun: function (e) {
            console.log(e);
        }
    };
    json = $.extend({}, cApi.ajaxOption, json);
    $.ajax(json);
};
/*绑定跳转链接*/
$(function () {
    var stoneSeaObj = sessionStorage.getItem('stoSeaSessionObj');
    $('.menu-list').click(function () {
        var url = $(this).attr('data-url');
        var thisUrl = location.href;
        if ((url == 'friend-audit' && thisUrl.indexOf('friend-audit-detail') > -1) || (stoneSeaObj && url == 'stone-img' && thisUrl.indexOf('stone-img-detail') > -1)) {
            history.go(-1);
        } else {
            window.location.href = url + '.html';
        }
    })
    //*点击有子菜单的菜单栏*/
    $('.bar-blo').click(function () {
        var status = $(this).parents('.bar-list').hasClass('open-bar');
        console.log(status);
        if (status) {
            $(this).parents('.bar-list').removeClass('open-bar');
            $(this).parents('.bar-list').addClass('close-bar');
            $(this).find('img').removeClass('showBarImg');
            $(this).find('img').addClass('hideBarImg');
        } else {
            $(this).parents('.bar-list').addClass('open-bar');
            $(this).parents('.bar-list').removeClass('close-bar');
            $(this).find('img').addClass('showBarImg');
            $(this).find('img').removeClass('hideBarImg');
        }
    });
});
//获取手机验证码
function GetPhoneCode(cApi, count) {
    this.count = count;
    this.cApi = cApi;
    this.isClickCode = true;
}
GetPhoneCode.prototype = {
    //验证码倒计时
    countDown: function () {
        var that = this;
        var count = this.count;
        this.isClickCode = false;
        $('#phoneCode').addClass('mesBtnNoClick');
        // countDown = count + ' 秒';
        var setTime = setInterval(counter, 1000);

        function counter() {
            if (that.isClickCode == true) { //短信验证码请求失败时清除计时器
                clearInterval(setTime);
                count = that.count;
                $('#phoneCode').text('获取');
                $('#phoneCode').removeClass('mesBtnNoClick');
            } else {
                if (count == 1) {
                    that.isClickCode = true;
                    clearInterval(setTime);
                    $('#phoneCode').text('重新获取');
                    $('#phoneCode').removeClass('mesBtnNoClick');
                } else {
                    count--;
                    $('#phoneCode').text(count + ' 秒');
                }
            }
        }
    },
    //停止倒计时
    stopCountDown: function () {
        this.isClickCode = true;
    },
    //获取手机验证码
    getMsgCode: function (mobilePhone) {
        if (this.isClickCode) {
            var that = this;
            this.countDown();
            var json = {
                url: this.cApi.hostUrl + 'sendMSG.do',
                data: "weChatKey=9237B361957490BA9644A710A5E3DD84&&Data={mobilePhone:" + mobilePhone + "}",
                success: function (data) {
                    console.log(data);
                    if (data.Result) {
                        toastr.success('短信验证码发送成功！');
                    } else {
                        that.isClickCode = true;
                        toastr.error(data.MSG_CODE);
                        $('#phoneCode').text('重新获取');
                    }
                },
                errorFun: function (e) {
                    console.log(e);
                }
            };
            json = $.extend({}, this.cApi.ajaxOption, json);
            $.ajax(json);
        }
    },
}


function decodeByRegExp(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/%25/g, "\%");
    s = s.replace(/%2B/g, "\+");
    s = s.replace(/%26/g, "\&");

    return s;
}